package com.taoyibao.hongcanting.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;

import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.utils.LogUtils;

import java.io.File;

/**
 * @author TangAnna
 * @description: 下载Apk
 * @date :${DATA} 9:59
 */
public class DownApkServer extends Service {

    private static final String TAG = "DownApkServer";
    private Context context = this;

    public DownApkServer() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle downloadBundle = intent.getBundleExtra("download");
        if (downloadBundle != null) {
            String downloadUrl = downloadBundle.getString("downloadUrl");
            String title = downloadBundle.getString("title");
            String versionName = downloadBundle.getString("versionName");

            if (!TextUtils.isEmpty(downloadUrl)) {
                LogUtils.dNormal(TAG, "开始下载");
                long downloadId = downloadApk(downloadUrl, title, versionName);
                SpUtils.putDownloadId(downloadId);
            }
        }
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }


    private long downloadApk(String url, String title, String versionName) {
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        String apkName = title + versionName + ".apk";

        File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/" + apkName);
        if (file != null && file.exists()) {
            file.delete();
        }
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS,
                apkName);
        SpUtils.putApkName(apkName);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setTitle(title);
        DownloadManager mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        return mDownloadManager.enqueue(request);
    }
}
